#include <iostream>
#include <map>
#include <fstream>
#include <sstream>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::map;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;

class Dictionary
{
public:
       void read(const string &filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "ifs open file failed" << endl;
            return;
        }

        //因为磁盘读写速度慢，应该尽量减少次数
        /* string word; */
        /* while(ifs >> word){ */
        /* } */

        string line;
        while(getline(ifs,line)){
            istringstream iss(line);
            string word;
            while(iss >> word){
                //处理单词
                string newWord = dealWord(word);
                
                //尝试插入
                if(string() != newWord){
                    ++_dict[newWord];
                }
            }
        }

        ifs.close();
    }

    string dealWord(const string & word){
        for(size_t idx = 0; idx != word.size(); ++idx){
            if(!isalpha(word[idx])){
                return string();
            }
        }
        return word;
    }



    void store(const string &filename){
        ofstream ofs(filename);
        if(!ofs){
            cerr << "ofs open file failed" << endl;
            return;
        }

        map<string,int>::iterator it = _dict.begin();
        for(; it != _dict.end(); ++it){
            ofs << it->first << "  " << it->second << endl; 
        }

        ofs.close();
    }
private:
    map<string,int> _dict;
};


void test0(){
    Dictionary dict;
    dict.read("The_Holy_Bible.txt");
    dict.store("dict.txt");
}

int main(void){
    test0();
    return 0;
}
